﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Runtime.Session;
using Mt.Site.Application.SEO.Dto;
using Mt.Site.Core.SEO;
using System;
using System.Globalization;
using System.Threading.Tasks;

namespace Mt.Site.Application.SEO
{
    public class SeoFrontEndAppService  : ApplicationService, ISeoFrontEndAppService
    {
        private readonly IRepository<Seo, Guid> _seoRepository;

        public SeoFrontEndAppService(
            IRepository<Seo, Guid> seoRepository)
        {
            LocalizationSourceName = MtSiteConsts.LocalizationSourceName;
            _seoRepository = seoRepository;
        }

        public async Task<SeoDto> GetSeo(GetSeoInput input)
        {
            if (input.JoinStr.IsNullOrEmpty())
            {
                input.JoinStr = "-";
            }

            if (input.RelatedId.HasValue)
            {
                var entity = await _seoRepository.FirstOrDefaultAsync(s => s.RelatedId == input.RelatedId.Value);
                if (entity != null)
                {
                    var dto = ObjectMapper.Map<SeoDto>(entity);
                    if (!input.GetForEdit)
                    {
                        if (!input.Mid_Str.IsNullOrEmpty())
                        {
                            dto.Title = string.Format(dto.Title, input.JoinStr + input.Mid_Str);
                        }
                        else
                        {
                            dto.Title = string.Format(dto.Title, input.Mid_Str);
                        }
                    }

                    return dto;
                }
            }
            return GetDefaultSeo(input);
        }

        private SeoDto GetDefaultSeo(GetSeoInput input)
        {
            //使后台的Seo编辑时也能调取到正确的默认值。
            string siteName = L("ApplicationName", CultureInfo.GetCultureInfo(AbpSession.CultureName()));

            string title;
            if (input.DefaultTitle.IsNullOrEmpty())
            {
                title = siteName;
            }
            else
            {
                if (input.Mid_Str.IsNullOrEmpty())
                {
                    title = $"{input.DefaultTitle}{input.JoinStr}{siteName}";
                }
                else
                {
                    title = $"{input.DefaultTitle}{input.JoinStr}{input.Mid_Str}{input.JoinStr}{siteName}";
                }
            }

            return new SeoDto()
            {
                Title = title
            };
        }
    }
}
